package com.lkd.http.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.lkd.common.VMSystem;
import com.lkd.config.ConsulConfig;
import com.lkd.config.TopicConfig;
import com.lkd.contract.OrderCheck;
import com.lkd.contract.VendoutContract;
import com.lkd.contract.VendoutData;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.OrderEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.service.OrderService;
import com.lkd.utils.ConvertUtils;
import com.lkd.utils.DistributedLock;
import com.lkd.vo.PayVO;
import com.lkd.vo.VmVO;
import com.lkd.wxpay.WXConfig;
import com.lkd.wxpay.WxPayDTO;
import com.lkd.wxpay.WxPaySDKUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private WxPaySDKUtil wxPaySDKUtil;
    @Autowired
    private OrderService orderService;
    @Autowired
    private MqttProducer mqttProducer;
    @Autowired
    private VMService vmService;
    @Autowired
    private ConsulConfig consulConfig;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 微信小程序支付
     * @param payVO
     * @return
     */
    @PostMapping("/weixinPay")
    public String createOrder(@RequestBody PayVO payVO){
        if(!vmService.hasCapacity(payVO.getInnerCode()
                ,Long.valueOf(payVO.getSkuId()))){
            throw new LogicException("该商品已售空");
        }
        //分布式锁，机器同一时间只能处理一次出货、
        DistributedLock lock = new DistributedLock(
                consulConfig.getConsulRegisterHost(),
                consulConfig.getConsulRegisterPort());
        DistributedLock.LockContext lockContext = lock.getLock(payVO.getInnerCode(), 60);
        if (!lockContext.isGetLock()){
            //不能获取锁
            throw new LogicException("机器出货中");
        }
        //获得锁，把sessionId存到redis中,过期时间
        redisTemplate.boundValueOps(VMSystem.VM_LOCK_KEY_PREF+payVO.getInnerCode())
                .set(lockContext.getSession(), Duration.ofSeconds(60));

        //创建订单
        OrderEntity orderEntity = orderService.createOrder(payVO);
        //封装OrderCheck,向EMQ发送延迟消息
        OrderCheck orderCheck = new OrderCheck();
        orderCheck.setOrderNo(orderEntity.getOrderNo());
        orderCheck.setInnerCode(orderEntity.getInnerCode());
        //发送延迟消息
        try {
            log.info("发送消息");
            mqttProducer.send("$delayed/600/"+TopicConfig.ORDER_CHECK_TOPIC,2,orderCheck);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //封装支付请求对象调用支付
        WxPayDTO wxPayDTO = new WxPayDTO();
        wxPayDTO.setBody(orderEntity.getSkuName());
        wxPayDTO.setOutTradeNo(orderEntity.getOrderNo());
        wxPayDTO.setTotalFee(orderEntity.getAmount().intValue());
        wxPayDTO.setOpenid(orderEntity.getOpenId());

        return wxPaySDKUtil.requestPay(wxPayDTO);
    }


    /**
     * 微信支付回调接口
     * @param request
     * @return
     */
    @RequestMapping("/payNotify")
    @ResponseBody
    public void payNotify(HttpServletRequest request, HttpServletResponse response){
        log.info("执行微信回调方法");
        try {
          /*  //输入流转换为xml字符串
            String notifyResult = ConvertUtils.convertToString(request.getInputStream());
            //解析xml字符串，得到订单号，如果为null,则表示支付失败
            String orderSn  = wxPaySDKUtil.validPay(notifyResult);*/

            String orderSn="01000001235094966144800";
            if (orderSn!=null){
                //支付成功，修改订单状态和支付状态
                log.info("修改订单状态和支付状态");
                //查询订单
                OrderEntity orderEntity = orderService.getByOrderNo(orderSn);
                if (orderEntity!=null){
                    orderEntity.setStatus(VMSystem.ORDER_STATUS_PAYED);//支付成功
                    orderEntity.setPayStatus(VMSystem.PAY_STATUS_PAYED);//支付成功
                    //更新订单状态
                    orderService.updateById(orderEntity);
                    //给微信支付一个成功的响应
                    response.setContentType("text/xml");
                    response.getWriter().write(WXConfig.RESULT);
                    //封装出货协议，发送出货协议到售货机服务
                    VendoutContract vendoutContract = new VendoutContract();
                    VendoutData vendoutData = new VendoutData();
                    vendoutData.setOrderNo(orderEntity.getOrderNo());
                    vendoutData.setSkuId(orderEntity.getSkuId());
                    vendoutContract.setVendoutData(vendoutData);
                    vendoutContract.setInnerCode(orderEntity.getInnerCode());
                    //发送消息
                    log.info("发送出货协议");
                    mqttProducer.send(TopicConfig.VMS_VENDOUT_TOPIC,2,vendoutContract);
                }
            }
        } catch (Exception e) {
            log.error("支付回调处理失败",e);
        }

    }


}
